package com.hyfrogx.modules.zoom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hyfrogx.common.exception.MyException;
import com.hyfrogx.common.param.PayType;
import com.hyfrogx.common.utils.QueryExt;
import com.hyfrogx.modules.app.service.UserService;
import com.hyfrogx.modules.app.utils.FrogConstant;
import com.hyfrogx.modules.manage.entity.payrecord.HyPayRecord;
import com.hyfrogx.modules.manage.service.HyPayRecordService;
import com.hyfrogx.modules.zoom.dao.HyPowerOrderDao;
import com.hyfrogx.modules.zoom.entity.HyNmtPower;
import com.hyfrogx.modules.zoom.entity.HyPowerOrder;
import com.hyfrogx.modules.zoom.entity.HyPowerUser;
import com.hyfrogx.modules.zoom.service.HyNmtPowerService;
import com.hyfrogx.modules.zoom.service.HyPowerOrderService;
import com.hyfrogx.modules.zoom.service.HyPowerUserService;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：Li9527
 * @date ：Created in 2019-11-19 11:06
 * @description：${description}
 * @modified By：
 * @version: 1.0.0
 */
@Service("HyPowerOrderService")
public class HyPowerOrderServiceImpl extends ServiceImpl<HyPowerOrderDao, HyPowerOrder> implements HyPowerOrderService {

    @Autowired
    HyNmtPowerService nmtPowerService;

    @Autowired
    UserService userService;

    @Autowired
    HyPowerOrderDao powerOrderDao;

    @Autowired
    HyPayRecordService payRecordService;

    @Autowired
    HyPowerUserService powerUserService;

    @Override
    public Integer createPowerOrder(HyPowerOrder record) throws MyException {
        // 通过传过来的特权卡id查询出特权卡信息,生成特权卡消费明细
        HyNmtPower hyNmtPower = nmtPowerService.getById(record.getPid());
        if (hyNmtPower == null) {
            throw new MyException("特权卡id错误");
        }
        record.setOrderno(this.getOutNo());
        // 生成消费明细订单
        record.setPrice(hyNmtPower.getTprice());
        record.setTprice(0);
        record.setType(hyNmtPower.getType());
        record.setCapacity(hyNmtPower.getCapacity());
        record.setDuration(hyNmtPower.getDuration());
        record.setStartdate(new Date());
        // 计算出结束时间
        record.setEnddate(DateUtils.addMonths(new Date(), hyNmtPower.getDuration()));
        // 已进行扣费的用户,特权卡消费记录直接设置状态为已支付,web端生成的默认未支付
        record.setPayway(0);
        // 判断用户余额是否足够
        int money = userService.getMoneyByUid(record.getUid());
        if (money < hyNmtPower.getTprice()) {
            // 待支付
            record.setStatus(FrogConstant.Status.FLASE);
            powerOrderDao.insert(record);
            throw new MyException("余额不足");
        }
        // 够扣,开始扣费
        userService.reduce(record.getUid(), hyNmtPower.getTprice());
        record.setTprice(hyNmtPower.getTprice());
        record.setPayway(0);
        record.setStatus(FrogConstant.Status.TRUE);
        powerOrderDao.insert(record);
        this.costOrder(record.getUid(), hyNmtPower);

        // 查询该方数的特权卡用户是否有买过(但要区分普通和专属)
        HyPowerUser powerUser = powerUserService.getOne(new QueryWrapper<HyPowerUser>().eq("capacity",record.getCapacity()).eq(
                "uid",record.getUid()).eq("type",record.getType()));
        // 如果是初次购买此权益
        if (powerUser == null) {
            // 添加该项权益
            HyPowerUser npHyPowerUser = new HyPowerUser();
            npHyPowerUser.setUid(record.getUid());
            npHyPowerUser.setPid(record.getPid());
            npHyPowerUser.setType(record.getType());
            npHyPowerUser.setCapacity(record.getCapacity());
            npHyPowerUser.setDuration(record.getDuration());
            npHyPowerUser.setStatus(FrogConstant.Status.TRUE);
            npHyPowerUser.setStartdate(new Date());
            npHyPowerUser.setEnddate(DateUtils.addMonths(new Date(), record.getDuration()));
            // 权益继承原来订单里的会议室名称
            if(record.getMeetName() != null){
                npHyPowerUser.setName(record.getMeetName());
            }
            powerUserService.save(npHyPowerUser);
        } else {
            // 查看是否已过期
            if (powerUser.getEnddate().getTime() < System.currentTimeMillis()) {
                // 已过期,直接重置该项权益购买时间,到期时间,重置状态为有效
                powerUser.setStatus(FrogConstant.Status.TRUE);
                powerUser.setStartdate(new Date());
                powerUser.setEnddate(DateUtils.addMonths(new Date(), record.getDuration()));
            } else {
                // 没过期,只需要在到期时间基础上,再加上该特权的到期时间
                powerUser.setEnddate(DateUtils.addMonths(powerUser.getEnddate(), record.getDuration()));
                powerUser.setDuration(record.getDuration() + powerUser.getDuration());
            }
            // 权益继承原来订单里的会议室名称
            if(record.getMeetName() != null){
                powerUser.setName(record.getMeetName());
            }
            powerUserService.updateById(powerUser);
        }
        return 1;
    }

    @Override
    public Page selectPageByConditions(QueryExt query) {
        Map map = new HashMap();
        map.putAll(query.getCondition());
        query.setRecords(powerOrderDao.selectPageByConditions(query, map));
        return query;
    }

    public String getOutNo() {
        Calendar now = Calendar.getInstance();
        int year = now.get(Calendar.YEAR);
        int month = now.get(Calendar.MONTH) + 1;
        String monthN;
        if(month < 10){
            monthN = "0" + month + "";
        }else{
            monthN = month + "";
        }
        int day = now.get(Calendar.DAY_OF_MONTH);
        String outNo = year + "" + monthN  + day  + "" +  System.currentTimeMillis() + "";
        return outNo;
    }

    public int costOrder(Long uid, HyNmtPower nmtPower) {
        // TODO Auto-generated method stub
        // 生成订单
        HyPayRecord payRecord = new HyPayRecord();
        payRecord.setCreatedate(new Date());
        payRecord.setTotal(nmtPower.getTprice());
        payRecord.setMoney(0);
        payRecord.setNum(0);
        payRecord.setType(PayType.mnt_power_buy.getCode());
        payRecord.setYid(FrogConstant.admin_uid);
        // 扣费者id
        payRecord.setUid(uid);
        // 资源对应id(本次为抽取无资源)
        payRecord.setSid(nmtPower.getId());
        payRecordService.save(payRecord);
        return 1;
    }








}
